<?php
namespace Api\Controller;
use Common\Controller\ApiController;
use Common\ORG\PublicFunction;
use Common\ORG\WxFunction;
use Think\Db;


/**

 * 用户资料

 *

 * 用户资料相关信息操作。

 * @Author      LD(191696242@qq.com)

 * @Version     1.o

 * @Date        2020/12/23

 * @Time        16:00

 * @since

 */
class MembersResumeController extends ApiController{

    private $resume = [];
    private $date   = '';
    public function _initialize()
    {
        parent::_initialize();
        if(!IS_POST){
            $this->ajaxReturn(1, '提交方式错误！');
        }

        if(!empty($this->userinfor['utype']) && $this->userinfor['utype']==1){
            $this->ajaxReturn(1, '企业用户不能添加用户资料！');
        }
        $this->resume   = $this->isResume();
        $this->date     = date('Y-m');
        $uid            = I('post.uid', 0,'intval');
        $id             = I('post.id', 0,'intval');

        if (ACTION_NAME<>'basicInfo' && !$this->resume && empty($uid) && empty($id)) {
            $this->ajaxReturn(4, '用户简历信息不存在！');
        }
    }

    /**
     * basicInfo
     * 用户资料添加

     * 添加用户基础信息资料

     * @access public

     * @param int       $id (必填：否) 简历ID  修改的时候必填
     * @param int       $advisorLevel (必填：否) 顾问等级 必须是人才顾问有效 1初级 2金牌一 3金牌二 4金牌三 5铂金 6钻石 7皇冠
     * @param int       $display (必填：是) 简历可见权限 0都可见 1招聘方可见 2人才顾问可见
     * @param string    $fullname (必填：是) 姓名全名
     * @param int       $sex (必填：是) 性别 1男 2女
     * @param string    $birthdate (必填：是) 出生年月 2020-12-23
     * @param string    $first_work_date (必填：是)首次参加工作年份 2020-12
     * @param string    $householdaddress (必填：否) 籍贯户籍地
     * @param string    $residence (必填：是) 居住地
     * @param string    $telephone (必填：是) 手机号
     * @param string    $email (必填：是) 邮箱
     * @param int       $marriage (必填：否) 婚姻状态 1未婚 2已婚 3保密
     * @param string    $country (必填：否) 国籍
     * @param string    $political (必填：否) 政治面貌
     * @param string    $year_income (必填：否) 年收入

     * @since

     * @return json

     */
    public function basicInfo(){
        $id     = I('post.id', 0, 'intval');//简历ID如果存在则修改
        $user   = $this->userinfo;
        $ints   = array('advisor_level', 'display', 'sex', 'marriage');
        $trims  = array('fullname', 'birthdate', 'first_work_date', 'householdaddress', 'residence', 'telephone', 'email', 'country', 'political', 'year_income');
        foreach ($ints as $val) {
            $setSqlArr[$val] = I('post.' . $val, 0, 'intval');
        }
        foreach ($trims as $val) {
            $setSqlArr[$val] = I('post.' . $val, '', 'trim,badword');
        }
        $setSqlArr['def']   = 1;
        $setSqlArr['stime'] = time();
        $city       = D('CategoryDistrict')->custom_district_cache();
        if(empty($id) && $user['utype']==3){
            if(empty($setSqlArr['advisor_level'])) $this->ajaxReturn(1, '人才顾问等级不能为空');

            if($setSqlArr['advisor_level'] > 2) $this->ajaxReturn(1, '人才顾问类型错误');
        }

        if ($setSqlArr['display'] > 2) $this->ajaxReturn(1, '查看权限参数错误');

        if (empty($setSqlArr['fullname']) || !fieldRegex($setSqlArr['fullname'],'user')) {
            $this->ajaxReturn(1, '姓名不能为空，且只能包含汉子字母和数字');
        }

        if (!in_array($setSqlArr['sex'], [1,2])) $this->ajaxReturn(1, '性别类型参数错误');

        if (empty($setSqlArr['birthdate'])) $this->ajaxReturn(1, '出生年月不能为空');

        if (birthday($setSqlArr['birthdate']) < 18 ) $this->ajaxReturn(1, '注册用户必须年满18岁');

        if (empty($setSqlArr['first_work_date'])) $this->ajaxReturn(1, '首次参加工作年份不能为空');

        if(!empty($setSqlArr['householdaddress'])){
            $hujidi = explode('.', $setSqlArr['householdaddress']);
            $num    = count($hujidi);
            if(empty($city[$hujidi[$num-2]][$hujidi[$num-1]])) $this->ajaxReturn(1, '户籍地不存在');
        }
        if(empty($setSqlArr['residence'])) $this->ajaxReturn(1, '居住地不存在');

        $juzhudi    = explode('.', $setSqlArr['residence']);
        $jnum       = count($juzhudi);
        if(empty($city[$juzhudi[$jnum-2]][$juzhudi[$jnum-1]])) $this->ajaxReturn(1,'居住地不存在');

        if(empty($setSqlArr['telephone'])) $this->ajaxReturn(1, '手机号码不能为空');

        if(!fieldRegex($setSqlArr['telephone'],'mobile')) $this->ajaxReturn(1, '手机号格式不正确');

        if(empty($setSqlArr['email'])) $this->ajaxReturn(1, '邮箱地址不能为空');

        if(!fieldRegex($setSqlArr['email'],'email')) $this->ajaxReturn(1, '邮箱地址格式不正确');

        if(!empty($setSqlArr['marriage']) && !in_array($setSqlArr['marriage'], [1,2,3])) $this->ajaxReturn(1, '婚姻参数错误');

        if(!empty($setSqlArr['country']) && !fieldRegex($setSqlArr['country'],'user')) $this->ajaxReturn(1, '国籍不能包含除汉字数字字母外的非法字符');

        if(!empty($setSqlArr['political']) && !fieldRegex($setSqlArr['political'],'user')) $this->ajaxReturn(1, '政治面貌不能包含除汉字数字字母外的非法字符');

        if(!empty($setSqlArr['year_income']) && !fieldRegex($setSqlArr['year_income'],'user')) $this->ajaxReturn(1, '年收入不能包含除汉字数字字母外的非法字符');

        $resume = $this->isResume();
        if(empty($resume)){
            $res = D('Resume')->add_wx_resume($setSqlArr, $user);
        } else {
            $res = D('Resume')->save_wx_resume($setSqlArr, $resume['id'], $user);
        }

        if($res['status'] <> 0){
            $this->ajaxReturn(1, $res['error']);
        }

        if(empty($id)) {
            $this->ajaxReturn(0, $res['error'], $res['data']);
        }else{
            $this->ajaxReturn(0, $res['error']);
        }
    }



    /**
     * refreshtime
     * 刷新简历时间

     * 刷新用户简历时间

     * @access public

     * @param string

     * @since

     * @return json

     */
    public function refreshtime(){
        $setSqlArr['refreshtime'] = time();
        $res = D('Resume')->save_wx_resume($setSqlArr, $this->resume['id'], $this->userinfo);

        if($res['status'] <> 0){
            $this->ajaxReturn(1, $res['error']);
        }

        $this->ajaxReturn(0, '简历刷新成功');

    }


    /**
     * getBasicInfo
     * 获取用户资料

     * 获取用户基础信息资料

     * @access public

     * @since

     * @return json

     */
    public function getBasicInfo(){
        $id     = I('post.id', 0,'intval');//查询指定用户信息
        $uid    = I('post.uid', 0,'intval');//查询指定用户信息
        $where  = !empty($uid) ? ['uid' => $uid] : ['id' => $id];
        $resume = empty($id) && empty($uid) ? $this->resume : M('Resume')->where($where)->find();
        $user   = empty($id) && empty($uid) ? $this->userinfo : M('Members')->where(['uid'=> $resume['uid']])->find();

        if(empty($resume)) $this->ajaxReturn(4,'用户简历信息不存在');

        $is_show=I('is_show',0);// 是否显示  用户主动投递的就直接显示

        if(empty($user)) $this->ajaxReturn(3,'用户注册信息不存在');


        $political  = D('Category')->get_category_cache()['QS_political'];//政治面貌
        $trade      = D('CategoryMajor')->get_major_list();//工程分类
        $nature     = D('Category')->get_category_cache()['QS_dutytime'];//到岗时间
        $jobTag     = D('Category')->get_category_cache()['QS_jobtag'];//期望福利

        //获取全部职位类别
        $jobs       = explode(',', $resume['jobs_id']);
        $jobsName   = [];
        foreach($jobs as $val){
            $job_t      = explode('.', $val);
            $jid        = !empty($job_t[1]) ? $job_t[1] : $job_t[0];
            $jobsName[] = !empty(D('CategoryJobs')->getJobsName($jid)) ? D('CategoryJobs')->getJobsName($jid) : '';
        }

        //设置简历已查看
        if(C('visitor.utype') == 1){
            $view_log = M('ViewResume')->where(array('uid'=>C('visitor.uid'),'resumeid'=>$resume['id']))->find();
            if($view_log){
                M('ViewResume')->where(array('uid'=>C('visitor.uid'),'resumeid'=>$resume['id']))->setField('addtime',time());
            }else{
                M('ViewResume')->add(array('uid'=>C('visitor.uid'),'resumeid'=>$resume['id'],'resume_uid'=>$resume['uid'],'addtime'=>time()));
            }
     //var_dump($resume);//die;
           // if($_GET['jobs_id']){
                $apply_log = D('PersonalJobsApply')->check_jobs_apply($resume['id'],C('visitor.uid'),intval($_GET['jobs_id']));
          //  var_dump($apply_log);die;
                $apply_log && D('PersonalJobsApply')->set_apply($apply_log,C('visitor'),2);
           // }
        }


        //获取上传图片
        $imgs   = M("ResumeImg")->where(['uid'=>$user['uid'], 'resume_id'=> $resume['id'], 'audit'=>['in', [1,2]]])->select();
        foreach($imgs as &$item){
            $item['addtime']    = date('Y-m-d H:i:s', $item['addtime']);
            $item['img']        = C('qscms_site_domain') . __ROOT__ . '/data/upload/resume_img/'.$item['img'];
            unset($item['title'],$item['audit']);
        }

        //教育经历
        $educationList      = D('ResumeEducation')->get_resume_education($resume['id'], $user['uid']);
        $educationListNew   = [];
        foreach($educationList as &$val){
            $educationListNew[] = [
                "id"            => $val['id'],
                "pid"           => $val['pid'],
                "uid"           => $val['uid'],
                "school"        => $val['school'],
                "speciality"    => $val['speciality'],
                "education"     => $val['education'],
                "education_cn"  => $val['education_cn'],
                "start_date"    => $val['startyear'].'-'.str_pad($val['startmonth'],2,"0",STR_PAD_LEFT),
                "end_date"      => $val['endyear'].'-'.str_pad($val['endmonth'],2,"0",STR_PAD_LEFT),
            ];
        }
        unset($educationList);

        //工作单位项目经历

        $workList       = D('ResumeWork')->get_resume_work($resume['id'], $user['uid']);
        $workListNew    = [];
        foreach($workList as &$valw){
            $workListNew[] = [
                "id"            => $valw['id'],
                "pid"           => $valw['pid'],
                "uid"           => $valw['uid'],
                "companyname"   => $valw['companyname'],
                "projectname"   => $valw['projectname'],
                "content"       => $valw['content'],
                "jobs"          => $valw['jobs'],
                "achievements"  => $valw['achievements'],
                "address"       => $valw['address'],
                "start_date"    => $valw['startyear'].'-'.str_pad($valw['startmonth'],2,"0",STR_PAD_LEFT),
                "end_date"      => $valw['endyear'].'-'.str_pad($valw['endmonth'],2,"0",STR_PAD_LEFT),
            ];
        }
        unset($workList);

        //资格证书
        $credentList   = D('ResumeCredent')->get_resume_credent($resume['id'], $user['uid']);
        foreach($credentList as &$valc){
            $valc['year_month']  = $valc['year'].'-'.$valc['month'];
            unset($valc['year'],$valc['month'], $valc['images']);
        }

        //是否下载
        $down   = M("CompanyDownResume")->where(['resume_id'=>$resume['id'], 'company_uid'=>$this->userinfo['uid']])->find();

        //人才顾问判断是否问答通过
        //if($user['utype']==0) {
            $wenda = M('questionnaire_user_list')->where(['uid' => $user['uid']])->order('id desc')->find();
        //}

        //是否支付
        //$order  = M('Order')->where(['uid'=>$user['uid'], 'order_type'=>17, 'is_paid'=>2])->find();
        
        //获取擅长职位类别名称
        $goodJobsCn = [];
        if($resume['good_jobs']) {
            $gjarr  = explode(',', $resume['good_jobs']);
            foreach($gjarr as $jval) {
                $gj_t   = explode('.', $jval);
                $gjid   = !empty($gj_t[1]) ? $gj_t[1] : $gj_t[0];
                $goodJobsCn[]   = !empty(D('CategoryJobs')->getJobsName($gjid)) ? D('CategoryJobs')->getJobsName($gjid) : '';
            }
        }

        //获取擅长工程类别
        $goodTradeCn    = [];
        if($resume['good_trade']) {
            $gtarr      = explode(',', $resume['good_trade']);
            foreach($gtarr as $tval) {
                $t              = explode('.', $tval);
                $goodTradeCn[]  = !empty($t[1]) && !empty($trade[$t[1]]) ? $trade[$t[1]]['categoryname'] : (!empty($t[0]) && !empty($trade[$t[0]]) ? $trade[$t[0]]['categoryname'] : '');
            }
        }

        //期望福利
        $jobTagCn   = [];
        if($resume['job_tag']){
            $jtarr  =explode(',', $resume['job_tag']);
            foreach($jtarr as $jval) {
                $jobTagCn[]  = !empty($jobTag[$jval]) ? $jobTag[$jval] : '';
            }
        }

        $data   = [
            'id'            => $resume['id'],
            'avatars'       => avatar($user['uid']),
            'utype'         => $user['utype'],
            'advisor_level' => $user['advisor_level'] ? $user['advisor_level'] : '0', //顾问等级
            'advisor_level_name' => $user['advisor_level_name'] ? $user['advisor_level_name'] : '', //顾问等级名称
            'display'       => $resume['display'],  //简历可见权限 0都可见 1招聘方可见 2人才顾问可见
            'audit'         => $resume['audit'],
            'status'        => !empty($wenda) ? $wenda['status'] : '3',
            //'order_status'  => !empty($order) ? '1' : '0',
            'sex'           => $resume['sex'],      //性别
            'sex_cn'        => $resume['sex_cn'],   //性别明文
            'marriage'      => $resume['marriage'], //婚姻状态
            'marriage_cn'   => $resume['marriage_cn'],//婚姻状态明文
            'skill'         => $resume['skill'],    //特殊技能特长
            'fullname'      => $resume['fullname'], //姓名
            'birthdate'     => $resume['birthdate'],//出生年月
            'age'           => birthdayToAge($resume['birthdate']),//年龄
            'first_work_date'       => $resume['first_work_date'], //首次工作日期
            'householdaddress'      => $resume['householdaddress'], //籍贯户籍地
            'householdaddress_cn'   => D('CategoryDistrict')->getCityName($resume['householdaddress']),//籍贯户籍地明文
            'residence'     => $resume['residence'], //居住地
            'residence_cn'  => D('CategoryDistrict')->getCityName($resume['residence']), //居住地明文
//            'telephone'     => !empty($down) || (empty($uid) && empty($id)) || $is_show ? $resume['telephone'] : contact_hide($resume['telephone'],2),
//            'email'         => !empty($down) || (empty($uid) && empty($id)) || $is_show ? $resume['email'] : contact_hide($resume['email'],3),
             'telephone'     => !empty($down) || (empty($uid) && empty($id)) || $is_show ? $resume['telephone'] : '****',
             'email'         => !empty($down) || (empty($uid) && empty($id)) || $is_show ? $resume['email'] : '****',

            'country'       => $resume['country'],  //国籍
            'political'     => $resume['political'],//政治面貌
            'political_cn'  => !empty($political[$resume['political']]) ? $political[$resume['political']] : '',//政治面貌明文
            'year_income'   => $resume['year_income'],//年收入
            'level'         => $resume['level'], //简历完整度级别 1差 2良 3优
            'complete_percent'=> $resume['complete_percent'], //简历完整度%
            'stime'         => date('Y-m-d H:i:s', $resume['stime']),//保存时间
            'refreshtime'   => date('Y-m-d H:i:s', $resume['refreshtime']),//刷新时间
            'addtime'       => date('Y-m-d H:i:s', $resume['addtime']),//添加时间

            //自我描述
            'specialty'     => $resume['specialty'],//自我描述
            'good_trade'    => $resume['good_trade'],//擅长工程类别
            'good_trade_cn' => $goodTradeCn,//擅长工程明文
            'good_jobs'     => $resume['good_jobs'],//擅长职位类别
            'good_jobs_cn'  => $goodJobsCn,//擅长职位明文

            //求职信息
            'intention_jobs_id'     => $resume['intention_jobs_id'],//意向职位
            'intention_jobs'        => explode(',', $resume['intention_jobs']),//意向职位明文
            'jobs_id'               => $resume['jobs_id'],//职位类别ID
            'jobs_id_cn'            => $jobsName,//职位类别明文
            'trade'                 => $resume['trade'],//工程类别
            'trade_cn'              => explode(',', $resume['trade_cn']),//工程类别明文
            'district'              => $resume['district'],//期望工作地点
            'district_cn'           => explode(',', $resume['district_cn']),//期望工作地点明文
            'wage'                  => $resume['wage'],//薪资范围
            'wage_cn'               => $resume['wage_cn'],//薪资范围明文
            'nature'                => $resume['nature'],//期望工作性质
            'nature_cn'             => $resume['nature_cn'],//期望工作性质明文
            'current'               => $resume['current'],//求职状态
            'current_cn'            => $resume['current_cn'],//求职状态明文
            'duty_time'             => $resume['duty_time'],//期望到岗时间
            'duty_time_cn'          => !empty($nature[$resume['duty_time']]) ? $nature[$resume['duty_time']] : '',//期望到岗时间明文
            'job_tag'               => $resume['job_tag'],//期望福利
            'job_tag_cn'            => $jobTagCn,//期望福利

            //是否下载简历
            'down'                  => empty($down) ? '0' : '1',

            //教育经历
            'educationList' => $educationListNew,

            //工作单位/项目经历
            'workList'      => $workListNew,

            //语言能力
            'languageList'  => D('ResumeLanguage')->get_resume_language($resume['id'], $user['uid']),

            //资格证书
            'credentList'   => $credentList,

            //
            //上传文件类型
            'word'          => [
                'word_resume'           => !empty($resume['word_resume']) ? C('qscms_site_domain') . __ROOT__ . '/data/upload/word_resume/'.$resume['word_resume'] : '',
                'word_resume_title'     => $resume['word_resume_title'],
                'word_resume_addtime'   => !empty($resume['word_resume_title']) ? date('Y-m-d H:i:s', $resume['word_resume_title']) : '',
            ], //简历附件
            'other_word'          => [
                'other_word_resume'           => !empty($resume['other_word_resume']) ? C('qscms_site_domain') . __ROOT__ . '/data/upload/other_word_resume/'.$resume['other_word_resume'] : '',
                'other_word_resume_title'     => $resume['other_word_resume_title'],
                'other_word_resume_addtime'   => !empty($resume['other_word_resume_addtime']) ? date('Y-m-d H:i:s', $resume['other_word_resume_addtime']) : '',
            ], //其他简历附件
            'video'         => [
                'resume_video'           => !empty($resume['resume_video']) ? C('qscms_site_domain') . __ROOT__ . '/data/upload/resume_video/'.$resume['resume_video'] : '',
                'resume_video_title'     => $resume['resume_video_title'],
                'resume_video_addtime'   => !empty($resume['resume_video_addtime']) ? date('Y-m-d H:i:s', $resume['resume_video_addtime']) : '',
            ], //视频文件
            'resume_img'    => $imgs,//上传图片集合

        ];

        $this->ajaxReturn(0, 'ok', $data);

    }


    /**
     * saveSpecialty
     * 用户自我评价

     * 用户自我评价修改提交

     * @access public

     * @param string    $specialty (必填：是) 描述内容
     * @param string    $goodTrade (必填：否) 擅长工程类别  当用户utype==3为人才顾问必填
     * @param string    $goodJobs (必填：否) 擅长职位类别   当用户utype==3为人才顾问必填
     * @since

     * @return json

     */
    public function  saveSpecialty(){
        $user       = $this->userinfo;
        $specialty  = I('post.specialty', '', 'trim');
        $goodTrade  = I('post.good_trade', '', 'trim');
        $goodJobs   = I('post.good_jobs', '', 'trim');
        $data       = [
            'specialty' => $specialty
        ];

        if(empty($specialty)){
            $this->ajaxReturn(1, '描述内容不能为空！');
        }

        if($user['utype']==3 && empty($goodTrade)){
            $this->ajaxReturn(1, '顾问请填写擅长工程类别！');
        }

        if($user['utype']==3 && empty($goodJobs)){
            $this->ajaxReturn(1, '顾问请填写擅长职位类别！');
        }

        if(!empty($goodTrade)) {
            $data['good_trade'] = $goodTrade;
        }
        if(!empty($goodJobs)){
            $data['good_jobs'] = $goodJobs;
        }


        $rst = D('Resume')->save_wx_resume($data, $this->resume['id'], C('visitor'));
        if ($rst['status']) $this->ajaxReturn(1, $rst['error']);

        //添加职位和工程搜索
        if($goodTrade) {
            $goodTradearr   = explode(',', $goodTrade);
            foreach($goodTradearr as $tval) {
                if (!M('JobscateSearch')->where(['type' => 1, 'id_str' => $tval])->find()) {//擅长工程分类
                    $gtarr  = explode('.', $tval);
                    $tnum   = count($gtarr);
                    $strt    = !empty($tval[$tnum - 1]) ? $tnum[$tnum - 1] : $tnum[$tnum - 2];
                    M('JobscateSearch')->add(['type' => 1, 'id_str' => $tval, 'type_id' => $strt, 'addtime' => time()]);
                }
            }
        }
        if($goodJobs) {
            $goodJobsarr = explode(',', $goodJobs);
            foreach($goodJobsarr as $jval) {
                if (!M('JobscateSearch')->where(['type' => 2, 'id_str' => $jval])->find()) {//擅长职位分类
                    $gjarr  = explode('.', $jval);
                    $jnum   = count($gjarr);
                    $str    = !empty($jval[$jnum - 1]) ? $jval[$jnum - 1] : $jval[$jnum - 2];
                    M('JobscateSearch')->add(['type' => 2, 'id_str' => $jval, 'type_id' => $str, 'addtime' => time()]);
                }
            }
        }


        write_members_log(C('visitor'), 'resume', '保存简历自我描述（简历id：' . $this->resume['id'] . '）', false, array('resume_id' => $this->resume['id']));
        $this->ajaxReturn(0, '简历自我描述修改成功');

    }



    /**
     * saveSkill
     * 用户其他技能特长

     * 用户自我评价修改提交

     * @access public

     * @param string    $skill (必填：是) 描述内容
     * @since

     * @return json

     */
    public function  saveSkill(){
        $skill  = I('post.skill', '', 'trim,badword');
        $data   = [
            'skill' => $skill
        ];

        if(empty($skill)){
            $this->ajaxReturn(1, '参数不能为空！');
        }

        $rst = D('Resume')->save_wx_resume($data, $this->resume['id'], C('visitor'));
        if ($rst['status']) $this->ajaxReturn(1, $rst['error']);
        write_members_log(C('visitor'), 'resume', '保存简历特殊技能（简历id：' . $this->resume['id'] . '）', false, array('resume_id' => $this->resume['id']));
        $this->ajaxReturn(0, '技能保存成功');

    }

    /**
     * saveBasic
     * 求职信息

     * 用户求职信息修改提交

     * @access public

     * @param string    $intentionJobs (必填：是) 意向职位 手动输入
     * @param string    $jobsId (必填：是) 职位类别    职位分类depth字段 多个选项逗号间隔提交
     * @param string    $trade (必填：是) 工程类别     工程分类ID 多个ID逗号间隔 cn
     * @param string    $district (必填：是) 期望工作地点     depth字段 多个选项逗号间隔提交 cn
     * @param string    $wage (必填：是) 期望薪资范围     薪资范围ID cn
     * @param string    $nature (必填：是) 期望工作性质     工作性质ID cn
     * @param string    $current (必填：是) 求职状态     求职状态ID cn
     * @param string    $dutyTime (必填：是) 期望到岗时间     到岗时间分类ID
     * @param string    $jobTag (必填：是) 期望福利     期望福利ID
     * @since

     * @return json

     */
    public function saveBasic()
    {
        $intentionJobs      = I('post.intention_jobs', '', 'trim');//意向职位
        $jobsId             = I('post.jobs_id', '', 'trim');//职位类别
        $trade              = I('post.trade', '', 'trim');//工程类别
        $district           = I('post.district', '', 'trim');//期望工作地点
        $wage               = I('post.wage', 0, 'intval');//期望薪资范围
        $nature             = I('post.nature', 0, 'intval');//期望工作性质
        $current            = I('post.current', 0, 'intval');//求职状态
        $dutyTime           = I('post.duty_time', 0, 'intval');//期望到岗时间
        $jobTag             = I('post.job_tag', 0, 'trim');//期望福利

        if(empty($intentionJobs)){
            $this->ajaxReturn(1, '请填写意向职位！');
        }

        if(empty($jobsId)){
            $this->ajaxReturn(1, '请至少添加一个职位类别！');
        }

        if(empty($trade)){
            $this->ajaxReturn(1, '请至少添加一个工程类别！');
        }

        if(empty($district)){
            $this->ajaxReturn(1, '请至少添加一个期望工作地点！');
        }

        if(empty($wage)){
            $this->ajaxReturn(1, '请选择期望薪资范围！');
        }

        if(empty($nature)){
            $this->ajaxReturn(1, '请选择期望工作性质！');
        }

        if(empty($current)){
            $this->ajaxReturn(1, '请选择求职状态！');
        }

        if(empty($dutyTime)){
            $this->ajaxReturn(1, '请选择期望到岗时间！');
        }
        $data       = [
            'intention_jobs'    => $intentionJobs,
            'jobs_id'           => $jobsId,
            'trade'             => $trade,
            'district'          => $district,
            'wage'              => $wage,
            'nature'            => $nature,
            'current'           => $current,
            'duty_time'         => $dutyTime,
        ];

        if(!empty($jobTag)){
            $data['job_tag']    = $jobTag;
        }

        $rst = D('Resume')->save_wx_resume($data, $this->resume['id'], C('visitor'));
        if ($rst['status']) $this->ajaxReturn(1, $rst['error']);

        write_members_log(C('visitor'), 'resume', '保存求职信息（简历id：' . $this->resume['id'] . '）', false, array('resume_id' => $this->resume['id']));
        $this->ajaxReturn(0, '求职信息保存成功！');
    }


    /**
     * saveEducation
     * 添加||修改教育经历

     * 教育经历添加修改提交

     * @access public

     * @param string    $id (必填：否) 修改的时候必填
     * @param string    $school (必填：是) 毕业院校
     * @param string    $education (必填：是) 学历ID   cn
     * @param string    $speciality (必填：是) 专业名称
     * @param string    $startDate (必填：是) 开始年月
     * @param string    $endDate (必填：是) 结束年月
     * @since

     * @return json

     */
    public function saveEducation()
    {
        $id         = I('post.id', 0, 'intval');//简历ID如果存在则修改
        $school     = I('post.school', '', 'trim,badword');//毕业院校
        $education  = I('post.education', 0, 'intval');//学历ID
        $speciality = I('post.speciality', '', 'trim,badword');//专业名称
        $startDate  = I('post.start_date', '', 'trim,badword');//开始年月
        $endDate    = I('post.end_date', '', 'trim,badword');//结束年月

        if(empty($school)) $this->ajaxReturn(1, '院校名称不能为空！');

        if(empty($education)) $this->ajaxReturn(1, '请选择学历！');

        if(empty($speciality)) $this->ajaxReturn(1, '请填写专业！');

        if(empty($startDate) || !fieldRegex($startDate, 'ym')) $this->ajaxReturn(1, '开始时间格式不正确！');

        if(empty($endDate) || !fieldRegex($endDate, 'ym')) $this->ajaxReturn(1, '结束时间格式不正确！');

        if ($startDate >= $this->date) $this->ajaxReturn(1, '就读开始时间不允许大于等于当前时间！');

        if($endDate > $this->date) $this->ajaxReturn(1,'就读结束时间不允许大于当前时间！');

        if ($startDate >= $endDate) $this->ajaxReturn(1, '就读开始时间不允许大于等于毕业时间！');

        $educations = D('Category')->get_category_cache('QS_education');
        if(empty($educations[$education]))  $this->ajaxReturn(1, '学历参数错误！');

        $startDateAll   = explode('-', $startDate);
        $endDateAll     = explode('-', $endDate);


        $data   = [
            'pid'       => $this->resume['id'],
            'uid'       => $this->userinfo['uid'],
            'startyear' => $startDateAll[0],
            'startmonth'=> $startDateAll[1],
            'endyear'   => $endDateAll[0],
            'endmonth'  => $endDateAll[1],
            'school'    => $school,
            'speciality'=> $speciality,
            'education' => $education,
            'education_cn'=> $educations[$education],
            'todate'    => 0,
            'campus_id' => 0
        ];
        if(D('ResumeEducation')->where($data)->find())   $this->ajaxReturn(1, '教育经历不能重复添加！');

        if ($id) {
            $data['id'] = $id;
            if(!D('ResumeEducation')->where(['id'=>$id, 'uid'=>$data['uid']])->find())  $this->ajaxReturn(1, '要修改的记录和你的信息不匹配，修改失败！');

            $reg = D('ResumeEducation')->save_wx_resume_education($data, C('visitor'));
        } else {
            /*$educationcount = M('ResumeEducation')->where(array('pid' => $setsqlarr['pid'], 'uid' => $setsqlarr['uid']))->count(); //获取教育经历数量
            if ($educationcount >= 6) $this->ajaxReturn(0, '教育经历不能超过6条！');*/
            $reg = D('ResumeEducation')->add_wx_resume_education($data, C('visitor'));
        }


        if ($reg['status']==0) {
            $maxEdu = M("ResumeEducation")->where(['uid'=>$this->userinfo['uid']])->order('education desc')->find();
            $resumeData = [];
            if(!empty($maxEdu)){
                $resumeData['education']    = $maxEdu['education'];
            }
            D('Resume')->save_resume($resumeData, $this->resume['id'], C('visitor'));
            $this->ajaxReturn(0, $reg['error'], $reg['id']);
        } else {
            $this->ajaxReturn(1, $reg['error']);
        }
    }

    /**
     * educationList
     * 教育经历列表

     * 获取当前教育经历列表

     * @access public

     * @param string
     *
     * @since

     * @return json

     */
    public function educationList(){

        $list   = D('ResumeEducation')->get_resume_education($this->resume['id'], $this->userinfo['uid']);
        $data   = [];
        foreach($list as &$val){
            $data[] = [
                "id"            => $val['id'],
                "pid"           => $val['pid'],
                "uid"           => $val['uid'],
                "school"        => $val['school'],
                "speciality"    => $val['speciality'],
                "education"     => $val['education'],
                "education_cn"  => $val['education_cn'],
                "start_date"    => $val['startyear'].'-'.str_pad($val['startmonth'],2,"0",STR_PAD_LEFT),
                "end_date"      => $val['endyear'].'-'.str_pad($val['endmonth'],2,"0",STR_PAD_LEFT),
            ];
        }
        unset($list);
        $this->ajaxReturn(0, 'ok', $data);
    }


    /**
     * educationDel
     * 删除教育经历

     * 删除当前用户的教育经历

     * @access public

     * @param string    $id (必填：是)
     * @since

     * @return json

     */
    public function educationDel(){
        $id         = I('post.id', 0, 'intval');
        if(empty($id)){
            $this->ajaxReturn(1, '删除的教育经历ID不能为空');
        }
        $education  = M('ResumeEducation')->where(['id'=>$id, 'uid'=> $this->userinfo['uid'], 'pid'=>$this->resume['id']])->find();
        if(empty($education)){
            $this->ajaxReturn(1, '删除的记录不存在');
        }

        if(M('ResumeEducation')->delete($id)){
            $this->ajaxReturn(0, '删除成功');
        }

        $this->ajaxReturn(1, '删除失败');
    }


    /**
     * saveWork
     * 添加||修改工作经历

     * 工作经历添加修改提交

     * @access public

     * @param string    $id (必填：否)   修改的时候必填
     * @param string    $school (必填：是) 毕业院校
     * @param string    $education (必填：是) 学历ID   cn
     * @param string    $speciality (必填：是) 专业名称
     * @param string    $startDate (必填：是) 开始年月
     * @param string    $endDate (必填：是) 结束年月
     * @since

     * @return json

     */
    public function saveWork()
    {
        $id             = I('post.id', 0, 'intval');//工作经历ID 如果存在则修改
        $companyname    = I('post.companyname', '', 'trim,badword');//单位
        $projectname    = I('post.projectname', '', 'trim,badword');//项目名称
        $jobs           = I('post.jobs', '', 'trim,badword');//职位名称
        $address        = I('post.address', '', 'trim,badword');//工作地点
        $achievements   = I('post.achievements', '', 'trim,badword');//工作内容
        $content        = I('post.content', '', 'trim,badword');//单位项目说明
        $startDate      = I('post.start_date', '', 'trim,badword');//开始年月
        $endDate        = I('post.end_date', '', 'trim,badword');//结束年月

        if(empty($companyname)) $this->ajaxReturn(1, '单位/项目名称不能为空！');

        if(empty($jobs)) $this->ajaxReturn(1, '所任职位不能为空！');

        if(empty($startDate) || !fieldRegex($startDate, 'ym')) $this->ajaxReturn(1, '开始时间格式不正确！');

        if(empty($endDate) || !fieldRegex($endDate, 'ym')) $this->ajaxReturn(1, '结束时间格式不正确！');

        if ($startDate >= $this->date) $this->ajaxReturn(1, '开始时间不允许大于等于当前时间！');

        if($endDate > $this->date) $this->ajaxReturn(1,'结束时间不允许大于当前时间！');

        if ($startDate >= $endDate) $this->ajaxReturn(1, '开始时间不允许大于等于结束时间！');

        if(empty($address)) $this->ajaxReturn(1, '工作地点不能为空！');

        $startDateAll   = explode('-', $startDate);
        $endDateAll     = explode('-', $endDate);

        $data   = [
            'pid'   => $this->resume['id'],
            'uid'   => $this->userinfo['uid'],
            'startyear' => $startDateAll[0],
            'startmonth'=> $startDateAll[1],
            'endyear'   => $endDateAll[0],
            'endmonth'  => $endDateAll[1],
            'companyname'=> $companyname,
            'projectname'   => $projectname,
            'content'   => $content,
            'jobs'      => $jobs,
            'achievements'=> $achievements,
            'address'     => $address,
            'todate'    => 0
        ];
        if(D('ResumeWork')->where($data)->find()) $this->ajaxReturn(1, '相同信息不能重复添加');
        if (!empty($id)) {
            $data['id'] = $id;
            if(!D('ResumeWork')->where(['id'=>$id])->find()) $this->ajaxReturn(1, '修改的信息不存在');
            $reg = D('ResumeWork')->save_wx_resume_work($data, C('visitor'));
        } else {
            $reg = D('ResumeWork')->add_wx_resume_work($data, C('visitor'));
        }

        if ($reg['status']==0) {
            $this->ajaxReturn(0, '工作经历保存成功！', $reg['id']);
        } else {
            $this->ajaxReturn(1, $reg['error']);
        }
    }

    /**
     * workList
     * 工作经历列表

     * 获取当前工作经历列表

     * @access public

     * @param string
     *
     * @since

     * @return json

     */
    public function workList(){

        $list   = D('ResumeWork')->get_resume_work($this->resume['id'], $this->userinfo['uid']);
        $data   = [];
        foreach($list as &$val){
            $data[] = [
                "id"            => $val['id'],
                "pid"           => $val['pid'],
                "uid"           => $val['uid'],
                "companyname"   => $val['companyname'],
                "projectname"   => $val['projectname'],
                "content"       => $val['content'],
                "jobs"          => $val['jobs'],
                "achievements"  => $val['achievements'],
                "address"       => $val['address'],
                "start_date"    => $val['startyear'].'-'.str_pad($val['startmonth'],2,"0",STR_PAD_LEFT),
                "end_date"      => $val['endyear'].'-'.str_pad($val['endmonth'],2,"0",STR_PAD_LEFT),
            ];
        }
        unset($list);
        $this->ajaxReturn(0, 'ok', $data);
    }


    /**
     * workDel
     * 删除工作经历

     * 删除当前用户的教育经历

     * @access public

     * @param string    $id (必填：是)
     * @since

     * @return json

     */
    public function workDel(){
        $id         = I('post.id', 0, 'intval');
        if(empty($id)){
            $this->ajaxReturn(1, '删除的工作/项目经历ID不能为空');
        }
        $education  = M('ResumeWork')->where(['id'=>$id, 'uid'=> $this->userinfo['uid'], 'pid'=>$this->resume['id']])->find();
        if(empty($education)){
            $this->ajaxReturn(1, '删除的记录不存在');
        }

        if(M('ResumeWork')->delete($id)){
            $this->ajaxReturn(0, '删除成功');
        }

        $this->ajaxReturn(1, '删除失败');
    }


    /**
     * saveLanguage
     * 添加||修改语言能力

     * 语言能力添加修改提交

     * @access public

     * @param string    $id (必填：否) 修改的时候必填
     * @param string    $language (必填：是) 语言种类
     * @param string    $level (必填：是) 熟练程度

     * @since

     * @return json

     */
    public function saveLanguage()
    {
        $id         = I('post.id', 0, 'intval');//工作经历ID 如果存在则修改
        $language   = I('post.language', 0, 'intval');//语言种类
        $level      = I('post.level', 0, 'intval');//熟练程度
        $category   = D('Category')->get_category_cache();

        if(empty($language)) $this->ajaxReturn(1, '语言种类不能为空！');

        if(empty($category['QS_language'][$language])) $this->ajaxReturn(1, '语言种类不存在！');

        if(empty($level)) $this->ajaxReturn(1, '熟练程度不能为空！');

        if(empty($category['QS_language_level'][$level])) $this->ajaxReturn(1, '熟练程度选项不存在！');

        $data   = [
            'pid'       => $this->resume['id'],
            'uid'       => $this->userinfo['uid'],
            'language'  => $language,
            'language_cn'=> $category['QS_language'][$language],
            'level'     => $level,
            'level_cn'  => $category['QS_language_level'][$level],
        ];

        if(D('ResumeLanguage')->where($data)->find()) $this->ajaxReturn(1, '相同信息不能修改或重复添加');
        if (!empty($id)) {
            $data['id'] = $id;
            if(!D('ResumeLanguage')->where(['id'=>$id])->find()) $this->ajaxReturn(1, '修改的信息不存在');
            $reg = D('ResumeLanguage')->save_wx_resume_language($data, C('visitor'));
        } else {
            $reg = D('ResumeLanguage')->add_wx_resume_language($data, C('visitor'));
        }

        if ($reg['status']==0) {
            $this->ajaxReturn(0, '语言能力保存成功！', $reg['id']);
        } else {
            $this->ajaxReturn(1, $reg['error']);
        }
    }

    /**
     * languageList
     * 语言能力列表

     * 获取当前语言能力列表

     * @access public

     * @param string
     *
     * @since

     * @return json

     */
    public function languageList(){

        $list   = D('ResumeLanguage')->get_resume_language($this->resume['id'], $this->userinfo['uid']);

        $this->ajaxReturn(0, 'ok', $list);
    }

    /**
     * languageDel
     * 删除语言能力

     * 删除当前用户的语言能力

     * @access public

     * @param string    $id (必填：是)

     * @since

     * @return json

     */
    public function languageDel(){
        $id         = I('post.id', 0, 'intval');
        if(empty($id)){
            $this->ajaxReturn(1, '删除ID不能为空');
        }
        $info  = M('ResumeLanguage')->where(['id'=>$id, 'uid'=> $this->userinfo['uid'], 'pid'=>$this->resume['id']])->find();
        if(empty($info)){
            $this->ajaxReturn(1, '删除的记录不存在');
        }

        if(M('ResumeLanguage')->delete($id)){
            $this->ajaxReturn(0, '删除成功');
        }

        $this->ajaxReturn(1, '删除失败');
    }



    /**
     * saveCredent
     * 添加||修改资格证书

     * 资格证书添加修改提交

     * @access public

     * @param string    $id (必填：否)   修改的时候必填
     * @param string    $name (必填：是) 证书名称
     * @param string    $grading (必填：是) 证书等级
     * @param string    $yearMonth (必填：是) 获取年月
     * @since

     * @return json

     */
    public function saveCredent()
    {
        $id         = I('post.id', 0, 'intval');//ID 如果存在则修改
        $name       = I('post.name', '', 'trim,badword');//证书名称
        $grading    = I('post.grading', '', 'trim,badword');//证书等级
        $yearMonth  = I('post.year_month', '', 'trim,badword');//获取年月

        if(empty($name)) $this->ajaxReturn(1, '证书名称不能为空！');

        if(strlen($name) > 60) $this->ajaxReturn(1, '证书名称大于20个汉字！');

        if(empty($grading)) $this->ajaxReturn(1, '证书等级不能为空！');

        if(empty($yearMonth) || !fieldRegex($yearMonth, 'ym')) $this->ajaxReturn(1, '获取时间格式不正确！');
        if(D('ResumeCredent')->where(['pid'=>$this->resume['id'], 'uid'=>$this->userinfo['uid']])->count() >= 10) $this->ajaxReturn(1,'资格证书已添加上限！');

        if($yearMonth > $this->date) $this->ajaxReturn(1,'获取时间不允许大于当前时间！');

        $yearMonthAll   = explode('-', $yearMonth);

        $data   = [
            'pid'       => $this->resume['id'],
            'uid'       => $this->userinfo['uid'],
            'name'      => $name,
            'grading'   => $grading,
            'year'      => $yearMonthAll[0],
            'month'     => $yearMonthAll[1],
        ];

        if(D('ResumeCredent')->where($data)->find()) $this->ajaxReturn(1, '相同信息不能重复添加或修改');
        if (!empty($id)) {
            $data['id'] = $id;
            if(!D('ResumeCredent')->where(['id'=>$id])->find()) $this->ajaxReturn(1, '修改的信息不存在');
            $reg = D('ResumeCredent')->save_wx_resume_credent($data, C('visitor'));
        } else {
            $reg = D('ResumeCredent')->add_wx_resume_credent($data, C('visitor'));
        }


        if ($reg['status']==0) {
            D('Resume')->save_resume('', $this->resume['id'], C('visitor'));
            $this->ajaxReturn(0, '证书保存成功！', $reg['id']);
        } else {
            $this->ajaxReturn(1, $reg['error']);
        }
    }

    /**
     * credentList
     * 资格证书列表

     * 获取当前资格证书列表

     * @access public

     * @param string
     *
     * @since

     * @return json

     */
    public function credentList(){

        $list   = D('ResumeCredent')->get_resume_credent($this->resume['id'], $this->userinfo['uid']);

        foreach($list as &$val){
            $val['year_month']  = $val['year'].'-'.$val['month'];
            unset($val['year'],$val['month'], $val['images']);
        }

        $this->ajaxReturn(0, 'ok', $list);
    }


    /**
     * credentDel
     * 删除语资格证书

     * 删除当前用户的资格证书

     * @access public

     * @param string    $id (必填：是)

     * @since

     * @return json

     */
    public function credentDel(){
        $id         = I('post.id', 0, 'intval');
        if(empty($id)){
            $this->ajaxReturn(1, '删除ID不能为空');
        }
        $info  = M('ResumeCredent')->where(['id'=>$id, 'uid'=> $this->userinfo['uid'], 'pid'=>$this->resume['id']])->find();
        if(empty($info)){
            $this->ajaxReturn(1, '删除的记录不存在');
        }

        if(M('ResumeCredent')->delete($id)){
            $this->ajaxReturn(0, '删除成功');
        }

        $this->ajaxReturn(1, '删除失败');
    }


    /**
     * imgDel
     * 删除用户照片集上传

     * 删除当前用户的资格证书

     * @access public

     * @param string    $id (必填：是)

     * @since

     * @return json

     */
    public function imgDel(){
        $id         = I('post.id', 0, 'intval');
        if(empty($id)){
            $this->ajaxReturn(1, '删除ID不能为空');
        }
        $info  = M('ResumeImg')->where(['id'=>$id, 'uid'=> $this->userinfo['uid'], 'resume_id'=>$this->resume['id']])->find();
        if(empty($info)){
            $this->ajaxReturn(1, '删除的记录不存在');
        }

        if(M('ResumeImg')->delete($id)){
            $this->ajaxReturn(0, '删除成功');
        }

        $this->ajaxReturn(1, '删除失败');
    }

    /**

     * modifyUser

     * 更改用户类型

     * 修改用户类型

     * @access public

     * @param int       $utype (必填) 用户类型

     * @param int       $advisorLevel (选填) 人才顾问等级

     * @since

     * @return json

     */
    public function modifyUser(){
        $user           = $this->userinfo;
        $utype          = I('post.utype', 0, 'intval');
        $advisorLevel   = I('post.advisor_level', 0, 'intval');

        if(!$utype || !in_array($utype, array(2,3))) $this->ajaxReturn(1, '用户类型为空或超出范围');

        if($utype==$this->userinfo['utype']) $this->ajaxReturn(1, '账户类型和要修改的类型一致，修改失败');


        $data   = ['utype'=> $utype];
        if($utype==3){
            if(!$advisorLevel) $this->ajaxReturn(1, '顾问等级不能为空');

            if($advisorLevel > 2) $this->ajaxReturn(1, '顾问等级类别错误');
            $level_info=M('guwen_level')->where(['level'=>$data['advisor_level']])->find();
            $data['advisor_level']      = $advisorLevel;
            $data['advisor_level_name'] = $level_info['name'];
        }

        if($utype==2){
            $order = D('order')->get_order_one(['uid'=>$user['uid'], 'utype'=>3, 'order_type'=>17, 'is_paid'=>2]);
            if($order) $this->ajaxReturn(1, '当前人才顾问不能变更账户类型！');
        }

        /////////////////////////////////////////////////////////////
        //修改用户搜索类型
        if(M('ResumeSearchFull')->where(['uid'=> $user['uid']])->find()) {
            M('ResumeSearchFull')->where(['uid' => $user['uid']])->save(['utype' => $utype]);
        }else{
            //M('ResumeSearchFull')->add(['uid' => $user['uid'], 'utype' => $utype]);
        }

        if(M('ResumeSearchPrecise')->where(['uid'=> $user['uid']])->find()) {
            M('ResumeSearchPrecise')->where(['uid' => $user['uid']])->save(['utype' => $utype]);
        }else{
            //M('ResumeSearchPrecise')->add(['uid' => $user['uid'], 'utype' => $utype]);
        }

        //成为人才顾问删除相关企业资料
        M('CompanyProfile')->where(['uid'=>$user['uid']])->delete();
        M('companyImg')->where(['uid'=>$user['uid']])->delete();//图片

        if($utype==2){
            M('QuestionnaireUserList')->where(['uid'=>$user['uid']])->delete();//修改求职者，删除问答
        }
        /////////////////////////////////////////////////////////////


        $res = M('Members')->where(['uid'=>$user['uid']])->save($data);
        if($res){
            $this->ajaxReturn(0, '用户类型更改成功');
        }else {
            $this->ajaxReturn(1, '用户类型更改失败');
        }

    }

    /**

     * modifyDisplay

     * 更改人才简历可见权限

     * 修改人才简历可见权限

     * @access public

     * @param int       $display (必填) 简历可见权限 0都可见 1招聘方可见 2人才顾问可见

     * @since

     * @return json

     */
    public function modifyDisplay(){
        $user           = $this->userinfo;
        $display        = I('post.display', 0, 'intval');
        if(!in_array($display, array(0,1,2))) $this->ajaxReturn(1, '简历可见权限参数不在范围内');

        if($user['utype']<>2) $this->ajaxReturn(1,'当前用户类型不允许修改');

        if(!$this->isResume())  $this->ajaxReturn(1,'简历信息不存在，请去创建');

        if(M('Resume')->where(['uid'=> $user['uid']])->save(['display'=>$display]))
            $this->ajaxReturn(0, '简历权限更改成功');
        else
            $this->ajaxReturn(1, '权限更改失败');

    }

}
?>